/**
 * 结合useMemo和useRef封装useCreation
 * 第一个参数是函数
 * 第二个参数是可变的数组
 */

import { useRef, DependencyList } from "react";

const depsAreSame = (oldDeps: DependencyList, deps: DependencyList): boolean => {
  if (oldDeps === deps) return true;

  for (let i = 0; i < oldDeps.length; i++) {
    // 判断两个值是否是同一个值
    if (!Object.is(oldDeps[i], deps[i])) return false;
  }

  return true;
};

interface CreationRef<T> {
  deps: DependencyList;
  obj: undefined | T;
  initialized: boolean;
}

const useCreation = <T>(fn: () => T, deps: DependencyList) => {
  const { current } = useRef<CreationRef<T>>({
    deps,
    obj: undefined,
    initialized: false
  });

  if (current.initialized === false || !depsAreSame(current.deps, deps)) {
    current.deps = deps;
    current.obj = fn();
    current.initialized = true;
  }

  return current.obj as T;
};

export default useCreation;
